package com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.R;
import com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.databinding.ActivityForgetPasswordBinding;
import com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.model.UserViewModel;
import com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.utils.GlobalViewModelStore;
import com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.utils.MyApplication;
import com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.utils.ValidationResult;
import com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.viewmodel.ForgetPasswordViewModel;

//忘记密码界面
public class ActivityForgetPassword extends AppCompatActivity {
    private ActivityForgetPasswordBinding binding;
    private ForgetPasswordViewModel viewModel;
    private String[] roles = {"parent", "doctor"};  //身份选择下拉框选项
    private int curRole = 0;    //当前选择的角色的序号
    private UserViewModel userViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 使用DataBinding方式初始化
        binding = DataBindingUtil.setContentView(this, R.layout.activity_forget_password);
        binding.setViewModel(viewModel);
        binding.setLifecycleOwner(this); // 重要！关联生命周期

        // 初始化ViewModel
        viewModel = new ViewModelProvider(this).get(ForgetPasswordViewModel.class);

        setUserViewModel();
        setSpinner();
        setupObservers();
        setupClickListeners();
    }

    private void setUserViewModel(){
        //用户身份
        // 获取全局共享的 UserViewModel
        userViewModel = GlobalViewModelStore
                .getInstance(MyApplication.getInstance())
                .get(UserViewModel.class);

    }

    private void setSpinner(){
        // 创建适配器，使用 strings.xml 中的数组资源
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this,
                R.array.roleArray,
                android.R.layout.simple_spinner_dropdown_item
        );
        // 设置下拉列表的样式
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // 将适配器设置给 Spinner
        binding.spinnerSelectRole.setAdapter(adapter);

        // 为 Spinner 添加选择监听器
        binding.spinnerSelectRole.setOnItemSelectedListener(new android.widget.AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(android.widget.AdapterView<?> parent, android.view.View view, int position, long id) {
                // 获取选中的值
                String selectedValue = parent.getItemAtPosition(position).toString();
                if (selectedValue.equals("医生")) {
                    curRole = 1;
                } else if (selectedValue.equals("家长")) {
                    curRole = 0;
                }
                userViewModel.setUserType(roles[curRole]);
            }

            @Override
            public void onNothingSelected(android.widget.AdapterView<?> parent) {
                // 当没有选择任何项时的处理
            }
        });
    }

    /** 初始化LiveData观察者 */
    private void setupObservers() {
        // 观察验证码生成（测试用）
        viewModel.getVerificationCode().observe(this, code -> {
            if (code != null) {
                Toast.makeText(this, "验证码已发送：" + code, Toast.LENGTH_LONG).show();
            }
        });

        // 观察倒计时更新
        viewModel.getCountdown().observe(this, seconds -> {
            binding.btnSendVerificationCode.setEnabled(seconds == 0);
            binding.btnSendVerificationCode.setText(
                    seconds > 0 ? String.format("%ds后重发", seconds) : "发送验证码"
            );
        });

        viewModel.getResetSuccess().observe(this, success -> {
            if (success != null && success) {
                Toast.makeText(this, "密码重置成功", Toast.LENGTH_SHORT).show();
                finish(); // 关闭当前页面
            }
        });

        viewModel.getResetError().observe(this, errorMsg -> {
            if (errorMsg != null) {
                Toast.makeText(this, errorMsg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /** 设置点击监听器 */
    private void setupClickListeners() {
        // 发送验证码按钮
        binding.btnSendVerificationCode.setOnClickListener(v -> {
            String account = binding.etAccount.getText().toString().trim();
            ValidationResult result = viewModel.validateAccount(account);

            if (result.isValid()) {
                viewModel.handleSendVerificationCode(account);
            } else {
                showValidationError(result.getErrorResId());
            }
        });

        // 提交按钮
        binding.btnLogin.setOnClickListener(v -> validateAndSubmit());
    }

    private void validateAndSubmit() {

        // 获取所有输入字段
        String account = binding.etAccount.getText().toString().trim();
        String code = binding.etVerificationCode.getText().toString().trim();
        String password = binding.etResetPassword.getText().toString().trim();
        String confirmPassword = binding.etConfirmPassword.getText().toString().trim();

        // 级联验证（按顺序检查）
        ValidationResult[] validations = {
                viewModel.validateAccount(account),
                viewModel.validateVerificationCode(code),
                viewModel.validatePassword(password),
                viewModel.validateConfirmPassword(confirmPassword)
        };

        // 查找第一个错误
        for (ValidationResult result : validations) {
            if (!result.isValid()) {
                showValidationError(result.getErrorResId());
                return;
            }
        }

        // 密码一致性验证
        if (!password.equals(confirmPassword)) {
            showValidationError(R.string.error_password_mismatch);
            return;
        }

        // 执行密码重置逻辑
        performPasswordReset(account, password, code);
    }

    // 修改performPasswordReset方法
    private void performPasswordReset(String account, String password, String code) {
        viewModel.performPasswordReset(account, password, code);

        // 可选：显示加载状态
        binding.progressBar.setVisibility(View.VISIBLE);
        binding.btnLogin.setEnabled(false);

        // 重置状态（根据实际需求）
        viewModel.getResetSuccess().observe(this, success -> {
            binding.progressBar.setVisibility(View.GONE);
            binding.btnLogin.setEnabled(true);
        });
    }

    /** 显示验证错误提示 */
    private void showValidationError(@StringRes int resId) {
        Toast.makeText(this, getString(resId), Toast.LENGTH_SHORT).show();
    }
}